

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * WritingFrm.java
 *
 * Created on 2011-10-24, 16:17:18
 */
package com.edu.kamai.client;

import com.edu.kamai.client.control.paperAnswerControl;
import com.edu.kamai.client.download.fileDownload;
import com.edu.kamai.client.upload.UploadPaper;
import com.edu.kamai.config.Constant;
import com.edu.kamai.media.audio.mp3Player;
import com.edu.kamai.media.audio.wavPlayer;
import com.edu.kamai.utility.FileName;
import com.edu.kamai.utility.TimeFormat;
import com.edu.kamai.xml.beans.writing.writingAnswer;
import com.edu.kamai.xml.beans.writing.writingQuestion;
import com.edu.kamai.xml.beans.writing.writingXML;
import com.edu.kamai.xmlparser.answerGeneration;
import com.edu.kamai.xmlparser.writing.writingAnswerGeneration;
import com.edu.kamai.xmlparser.writing.writingAnswerParser;
import com.edu.kamai.xmlparser.writing.writingPaperParser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.Timer;




/**
 *
 * @author xyzhu
 */
public class WritingFrm extends javax.swing.JFrame {

    /** Creates new form WritingFrm */
    //for student
    public WritingFrm(ContestFrm cf,String sn,String pp,int pid,int cID) {
        identity = 0;
        contestFrm = cf;
        sutdentName = sn;
        paperPath = pp;
        paperID = pid;
        contestID = cID;
        initComponents();
        initPaper();
        initAnswerPaper();
        initQuestion(questionIndex);
        setNet();
        
        writingTimer = new Timer(1000, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                exeTime++;
                TF_WritingTime.setText(TimeFormat.retTimeFormatting(exeTime));
                if(exeTime >= curLimit){
                    
                    
                }
                /*
                currentID = ssel.getDisplayNameID();
                String name = ssel.getDisplayNamebyID(currentID);
                displayArea.setText(name);
                 * 
                 */
                
            }
        });
        writingTimer.start();
        
    }

    //for teacher
    public WritingFrm(String tn,String pp,String app){
        identity = 1;
        paperPath = pp;
        answerPaperPath = app;
        initComponents();
        initPaper();
        initAnswerPaper();
        initQuestion(questionIndex);
        setNet();
        B_Submit.setEnabled(false);
        
        writingTimer = new Timer(1000, null);
    }
    
    
    
    private void setNet(){
        try{
            InputStream in = getClass().getResourceAsStream(Constant.netiniFilePath);
            Scanner scan = new Scanner(in);
            List<String> netList = new ArrayList<String>();
            
            while(scan.hasNextLine()){
                String line = scan.nextLine();
                if(!line.equals("")){
                    if(!line.startsWith("#")){
                        netList.add(line);
                    }
                }
            }
            paperAnswerControl.setNetList(netList);
            scan.close();
            in.close();
            
        }catch(Exception ex){
            ex.printStackTrace();
            //Control.setNetList(new ArrayList<String>());
        }
        paperAnswerControl.setServer();
    }
    
    private void showMessage(int ans,String msg){
        if(ans == 1){
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Done", ans);
        }else{
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Error", ans);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")


    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        B_Play = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TA_Writing = new javax.swing.JTextArea();
        B_Stop = new javax.swing.JButton();
        B_Prev = new javax.swing.JButton();
        B_Next = new javax.swing.JButton();
        TF_Title = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        TA_DES = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        TA_Main = new javax.swing.JTextArea();
        B_Submit = new javax.swing.JButton();
        TF_Limit = new javax.swing.JTextField();
        TF_WritingTime = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        B_Play.setText("Play");
        B_Play.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_PlayActionPerformed(evt);
            }
        });

        TA_Writing.setColumns(20);
        TA_Writing.setLineWrap(true);
        TA_Writing.setRows(5);
        jScrollPane1.setViewportView(TA_Writing);

        B_Stop.setText("Stop");
        B_Stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_StopActionPerformed(evt);
            }
        });

        B_Prev.setText("Prev");
        B_Prev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_PrevActionPerformed(evt);
            }
        });

        B_Next.setText("Next");
        B_Next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_NextActionPerformed(evt);
            }
        });

        TF_Title.setEditable(false);

        TA_DES.setColumns(20);
        TA_DES.setEditable(false);
        TA_DES.setLineWrap(true);
        TA_DES.setRows(5);
        jScrollPane2.setViewportView(TA_DES);

        TA_Main.setColumns(20);
        TA_Main.setEditable(false);
        TA_Main.setLineWrap(true);
        TA_Main.setRows(5);
        jScrollPane3.setViewportView(TA_Main);

        B_Submit.setText("submit");
        B_Submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_SubmitActionPerformed(evt);
            }
        });

        TF_Limit.setEditable(false);

        TF_WritingTime.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(B_Play)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(B_Stop)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(B_Prev, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                        .addComponent(B_Next, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(B_Submit))
                    .addComponent(TF_Title, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(TF_Limit, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123, Short.MAX_VALUE)
                        .addComponent(TF_WritingTime, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TF_Title, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(TF_Limit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(TF_WritingTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(B_Play)
                            .addComponent(B_Stop)
                            .addComponent(B_Prev)
                            .addComponent(B_Submit)
                            .addComponent(B_Next))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void B_PlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_PlayActionPerformed
        // TODO add your handling code here:
        
        String filename = localMp3Path;
        int pos = filename.lastIndexOf(".");
        String ext = filename.substring(pos + 1);
        if(ext.equalsIgnoreCase("mp3")){
            playMP3(filename);
        }else if(ext.equalsIgnoreCase("wma")){
            playWMA(filename);
        }
    }//GEN-LAST:event_B_PlayActionPerformed

    private void playMP3(String filename){
        try{
            wma = null;
            mp3 = new mp3Player(filename);
            mp3.play();
        }catch(Exception ex){
            mp3=null;
            showMessage(0, "did not suppout:" + filename);
            ex.printStackTrace();
        }finally{
            
        }
    }
    
    private void playWMA(String filename){
        try{
            mp3=null;
            wma = new wavPlayer(filename);
            wma.init();
            wma.start();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            playMP3(filename);
        }
    }
    
    private void B_StopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_StopActionPerformed
        // TODO add your handling code here:
        try{
            if(wma != null){
                wma.close();
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        
        try{
            if(mp3 != null){
                mp3.close();
            }
        }catch(Exception ex1){
            ex1.printStackTrace();
        }
    }//GEN-LAST:event_B_StopActionPerformed

    private void B_PrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_PrevActionPerformed
       /*
        wr = new wavRecord("test_zhu.wav");
        wr.capture();
         * 
         */
        if(questionIndex <= 0){
            showMessage(0,"no prev");
            return;
        }
        if(0 == identity){
            String content = TA_Writing.getText();
            wa.setWritingContent(questionIndex, content);
            questionIndex = questionIndex - 1;
            initQuestion(questionIndex);
        }else if(1 == identity){
            questionIndex = questionIndex - 1;
            TA_Writing.setText(wa.getWritingContent(questionIndex));
            initQuestion(questionIndex);
        }
    }//GEN-LAST:event_B_PrevActionPerformed

    private void B_NextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_NextActionPerformed
        // TODO add your handling code here:
        /*
        if(wr != null){
            wr.stop();
            wr.save();
        }
         * 
         */
        if(questionIndex >= totalQuestionCnt - 1){
            showMessage(0,"no next");
            return;
        }
        if(0 == identity){
            String content = TA_Writing.getText();
            wa.setWritingContent(questionIndex, content);
            questionIndex = questionIndex + 1;
            initQuestion(questionIndex);
        }else if(1 == identity){
            questionIndex = questionIndex + 1;
            TA_Writing.setText(wa.getWritingContent(questionIndex));
            initQuestion(questionIndex);
        }
    }//GEN-LAST:event_B_NextActionPerformed

    private void upLoadAnwerPaper(){
        
        String answerXMLName = "";
        answerGeneration axml = new writingAnswerGeneration(wa);
        axml.generateXML();
        answerXMLName = FileName.reNameWithCurrentTime(sutdentName);
        System.out.println(answerXMLName);
        axml.writeToDisk(answerXMLName);
        
        UploadPaper upp = new UploadPaper();
        upp.setFileName(answerXMLName);
        upp.start();
        
        int ans = paperAnswerControl.addPaperAnswer(Constant.WRITING_PAPER_ID, 
                Constant.upLoadPaperFileFolder + "/" + answerXMLName + ".xml", 
                0, paperID, sutdentName, contestID);
        
        showMessage(ans, paperAnswerControl.getMessage());
    }
    
    private void B_SubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_SubmitActionPerformed
        // TODO add your handling code here:
        if(wa != null){
            upLoadAnwerPaper();
            this.setVisible(false);
            contestFrm.setVisible(true);
        }else{
            showMessage(0, "Error no xml information!");
        }
    }//GEN-LAST:event_B_SubmitActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
      
    }//GEN-LAST:event_formWindowActivated
    
    private void initAnswerPaper(){
        if(0 == identity){
            wa = new writingAnswer(totalQuestionCnt);
            wa.setPaperID(paperID);
            wa.setUserID(sutdentName);
        }else if(1 == identity){
            writingAnswerParser wap = new writingAnswerParser(answerPaperPath);
            wa = wap.parseWritingAnswerXML();
        }
    }
    
    
    private void initQuestion(int index){
        B_Play.setEnabled(false);
        B_Stop.setEnabled(false);
        writingQuestion wq = wXml.getWritingquestionList().get(index);
        TF_Title.setText(wq.getPaperTitle());
        TA_DES.setText(wq.getPaperDescription());
        TA_Main.setText(wq.getMainTxt());
        String mp3Path = wq.getMp3Path();
        if(!mp3Path.equals("") && mp3Path != null){
            downloadMP3(mp3Path);
            B_Play.setEnabled(true);
            B_Stop.setEnabled(true);
        }
        TA_Writing.setText(wa.getWritingContent().get(index));
        String limit = wq.getTimeLimit();
        curLimit = Long.parseLong(limit);
        TF_Limit.setText(TimeFormat.retTimeFormatting(curLimit));
    }
    
    private void downloadMP3(String mp3Path){
        String url = Constant.urlAddress + "kamai_edu";
        url = url + mp3Path;
        int pos = mp3Path.lastIndexOf("/") + 1;
        String filename = FileName.getDefaultKamaiFolder() + mp3Path.substring(pos);
        localMp3Path = filename;
        File mp3 = new File(localMp3Path);
        if(!mp3.exists()){
            fileDownload fd = new fileDownload(url, filename);
            fd.start();
        }
    }
    
    private void initPaper(){
        wpp = new writingPaperParser(paperPath);
        wXml = wpp.parseWritingXML();
        totalQuestionCnt = wXml.getWritingquestionList().size();
        questionIndex = 0;
    }
   
    private final Timer writingTimer;
    private long exeTime;
    private long curLimit;
    
    private wavPlayer wma;
    private mp3Player mp3;
   /*
    wavRecord wr;
     * 
     */
    
    private int identity;
    private ContestFrm contestFrm;
    private writingAnswer wa;
    private String sutdentName;
    private String paperPath;
    private String answerPaperPath;
    private String localMp3Path;
    private int questionIndex;
    private int totalQuestionCnt;
    private int paperID;
    private int contestID;
    private writingPaperParser wpp;
    private writingXML wXml;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton B_Next;
    private javax.swing.JButton B_Play;
    private javax.swing.JButton B_Prev;
    private javax.swing.JButton B_Stop;
    private javax.swing.JButton B_Submit;
    private javax.swing.JTextArea TA_DES;
    private javax.swing.JTextArea TA_Main;
    private javax.swing.JTextArea TA_Writing;
    private javax.swing.JTextField TF_Limit;
    private javax.swing.JTextField TF_Title;
    private javax.swing.JTextField TF_WritingTime;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    // End of variables declaration//GEN-END:variables
}
